package com.nowcoder.community.endpoint;

import com.nowcoder.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
@Endpoint(id = "database") // 端点访问路径
public class DatabaseEndpoint {

    @Autowired
    private DataSource dataSource;

    /**
     * 检查数据库连接是否正常
     */
    @ReadOperation // GET 请求
    public String checkConnection() {
        try (Connection connection = dataSource.getConnection()) {
            return CommunityUtils.getJsonString(200, "获取数据库连接成功");
        } catch (SQLException e) {
            return CommunityUtils.getJsonString(500, "获取数据库连接失败：" + e.getMessage());
        }
    }
}
